package main

import (
	"fmt"
	"time"
)

func say(s string) {
	for i := 0; i < 5; i++ {
		time.Sleep(100 * time.Millisecond)
		fmt.Println(s)
	}
	channel()
}

func main() {
	// 并发调用
	go say("world")
	say("hello")
	// 声明通道
	ch := make(chan int)
	fmt.Println(ch)
	// 通道缓冲区
	c2 := make(chan int, 100)
	fmt.Println(c2)
	c3 := make(chan int)
	go test2(c3)
	x := <-c3
	fmt.Println(x)
	// go遍历与关闭通道
	c4 := make(chan int, 10)
	go fibonacci(cap(c4), c4)
	for v := range c4 {
		fmt.Println(v)
	}
}

func fibonacci(n int, c chan int) {
	x, y := 0, 1
	for i := 0; i < n; i++ {
		c <- x
		x, y = y, x+y
	}
	close(c)
}

func test2(c2 chan int) {
	c2 <- 1
}

// 两个goroutine计算数字之和
func channel() {
	var x = []int{1, 23, 123, 124, 1, 3213, 213, 21, 1}
	c := make(chan int)
	go sum(x[len(x)/2:], c)
	go sum(x[:len(x)/2], c)
	s, y := <-c, <-c
	fmt.Println(s, y)
}

// 求和
func sum(x []int, c chan int) {
	var sum int
	for _, v := range x {
		sum += v
	}
	c <- sum
}
